#include "netcheckmanager.h"

#include <iostream>

NetCheckManager::NetCheckManager()
    : m_netConnect(false)
    , m_threadRunning(true)
    , m_thread(new std::thread(&NetCheckManager::checkNetState, std::ref(*this)))
{
}

NetCheckManager::~NetCheckManager()
{
    {
        std::lock_guard<std::mutex> lock(m_mtx);
        m_checkers.clear();
        m_threadRunning = false;
        // 发送信号
        m_cv.notify_one();
    }
    m_thread->join();
    delete m_thread;
}

/**
 * @brief addChecker 添加一个检测者
 * @param checker
 * @param priority 优先级别，越小级别越高
 */
void NetCheckManager::addChecker(std::shared_ptr<AbstractChecker> checker, int priority)
{
    std::lock_guard<std::mutex> lock(m_mtx);
    m_checkers[priority].push_back(checker);
}

/**
 * @brief 检测状态
 * @note 该函数在线程中执行
 */
void NetCheckManager::checkNetState()
{
    // 操作共享资源之前先锁定互斥量
    std::unique_lock<std::mutex> lock(m_mtx);
    std::cout << "thread running..." << std::endl;
    while (true) {
    loop:
        // 等待信号
        m_cv.wait(lock);
        if (!m_threadRunning) {
            std::cout << "thread stop..." << std::endl;
            return;
        }

        for (auto items : m_checkers) {
            std::cout << "priority:" << items.first << std::endl;
            for (auto item : items.second) {
                if (item->check()) {
                    m_netConnect.store(true);
                    goto loop;
                }
            }
        }
        m_netConnect.store(false);
    }
}

/**
 * @brief 触发检测
 */
void NetCheckManager::startCheck()
{
    // 发送信号前先锁定互斥量
    std::lock_guard<std::mutex> lock(m_mtx);
    // 发送信号
    m_cv.notify_one();
}
